/**
 * 
 */
package com.jy.app.lib.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;

import java.io.File;

/**
 * @author NanCo
 *
 */
public class ApkUtils {

	public static PackageInfo getPackageInfo(Context context) {
		try {
			PackageManager pm = context.getPackageManager();
			PackageInfo pinfo = pm.getPackageInfo(context.getPackageName(),
					PackageManager.GET_CONFIGURATIONS);
			return pinfo;
		} catch (Exception e) {
			LogUtil.e("ApkUtils",e);
			return null;
		}

	}

	public static long getSDFreeSize(){
		try{
			//取得SD卡文件路径
			File path = Environment.getExternalStorageDirectory();
			StatFs sf = new StatFs(path.getPath());
			//获取单个数据块的大小(Byte)
			long blockSize = sf.getBlockSize();
			//空闲的数据块的数量
			long freeBlocks = sf.getAvailableBlocks();
			//返回SD卡空闲大小
			//return freeBlocks * blockSize;  //单位Byte
			//return (freeBlocks * blockSize)/1024;   //单位KB
			long size = (freeBlocks * blockSize)/1024 /1024;
			return size == 0?1024*1024*1024*500:size; //单位MB
		}catch (Exception e){
			return 1024*1024*1024*500; //单位MB
		}
	}


	public static String getVersionName(Context context) {
		try {
			PackageManager pm = context.getPackageManager();
			PackageInfo pinfo = pm.getPackageInfo(context.getPackageName(),
					PackageManager.GET_CONFIGURATIONS);
			return pinfo.versionName;
		} catch (Exception e) {
			return "";
		}
	}

	//版本号
	public static int getVersionCode(Context context) {
		try {
			PackageManager pm = context.getPackageManager();
			PackageInfo pinfo = pm.getPackageInfo(context.getPackageName(),
					PackageManager.GET_CONFIGURATIONS);
			return pinfo.versionCode;
		}catch (Exception e){
			return 0;
		}
	}
	
	/**
	 * install the apk
	 * 
	 * @param context
	 * @param filePath
	 */
	public static void install(Context context, String filePath) {
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + filePath),
				"application/vnd.android.package-archive");
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(i);
	}
	
	
}
